package sync;

public class TestLock {
    public static void main(String[] args) {
        new Person(0, "张三").start();
        new Person(1, "李四").start();
    }
}

class Person extends Thread {
    static Object goods1 = new Object();
    static Object goods2 = new Object();

    int choice;
    String name;

    Person(int choice, String name) {
        this.choice = choice;
        this.name = name;
    }

    @Override
    public void run() {
        try {
            getGoods();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void getGoods() throws InterruptedException {
        if (choice == 0) {
            synchronized (goods1) {
                System.out.println(this.getName() + "拿到goods1");
                Thread.sleep(1000);
                /*synchronized (goods2) {
                    System.out.println(this.getName() + "拿到goods2");
                }*/
            }
            synchronized (goods2) {
                System.out.println(this.getName() + "拿到goods2");
            }
        } else {
            synchronized (goods2) {
                System.out.println(this.getName() + "拿到goods1");
                Thread.sleep(2000);
                /*synchronized (goods1) {
                    System.out.println(this.getName() + "拿到goods2");
                }*/
            }
            synchronized (goods1) {
                System.out.println(this.getName() + "拿到goods2");
            }
        }
    }
}
